<?php
/*
 * Copyright 2010 Johannes M. Schmitt
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * This class runs the compiler given the compiler configuration.
 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
 */
class GoogleClosureCompilerRunner
{
	/**
	 * @var GoogleClosureCompilerConfiguration
	 */
	private $_configuration;
	
	/**
	 * Constructor
	 * @param GoogleClosureCompilerConfiguration $config
	 */
	public function __construct(GoogleClosureCompilerConfiguration $config)
	{
		$this->_configuration = $config;
	}
	
	/**
	 * Returns the configuration that is used by this compiler runner
	 * @return GoogleClosureCompilerConfiguration
	 */
	public final function getConfiguration()
	{
		return $this->_configuration;
	}
	
	/**
	 * Runs the compiler, and generates the different javascript files
	 */
	public function run()
	{
		$userAgents = $this->_configuration->getUserAgents();
		
		$jsFiles = array();
		// TODO: Compile the dependencies and return all required files
		// TODO: Compile a CSS renaming map, and add it as second javascript file
		
		// we need to compile one file for each combination of locale and user agent
		foreach ($this->_configuration->getLocales() as $locale)
		{
			if (count($userAgents) > 0)
			{
				foreach ($userAgents as $userAgent)
				{
					// TODO: Compile the script for different user agents
					$compiler = new GoogleClosureCompiler($jsFiles);
					$this->applyCommonConfiguration($compiler);
					$compiler->addDefine('goog.LOCALE', $locale);
					$compiler->addDefine('goog.ASSUME_'.$userAgent, true);
				}
			}
			else
			{
				// TODO: Compile the same script for all user agents
				$compiler = new GoogleClosureCompiler($jsFiles);
				$this->applyCommonConfiguration($compiler);
				$compiler->addDefine('goog.LOCALE', $locale);
			}
		}
	}
	
	/**
	 * Apply configuration settings that are common to all compiler instances
	 * @param GoogleClosureCompiler $compiler
	 */
	protected function applyCommonConfiguration(GoogleClosureCompiler $compiler)
	{
		foreach ($this->_configuration->getCompilerSettings()
							as $method => $argumentsCollection
		)
		{
			foreach ($argumentsCollection as $arguments)
			{
				call_user_func_array(array($compiler, $method), $arguments);
			}
		}
	}
}